class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int maxNum = n * n, curNum = 1;
        vector<vector<int>> matrix(n, vector<int>(n));
        int row = 0, col = 0, dirIndex = 0;
        vector<vector<int>> dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};  // 右下左上
        while (curNum <= maxNum)
        {
            matrix[row][col] = curNum;
            curNum++;
            int nextRow = row + dir[dirIndex][0], nextCol = col + dir[dirIndex][1];
            if (nextRow < 0 || nextRow >= n || nextCol < 0 || nextCol >= n || matrix[nextRow][nextCol] != 0)
            {
                dirIndex = (dirIndex + 1) % 4;  // 顺时针旋转至下一个方向
            }
            row = row + dir[dirIndex][0];
            col = col + dir[dirIndex][1];
        }
        return matrix;
    }
};